package com.cskaoyan.service.impl;

import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.pojo.MarketRegion;
import com.cskaoyan.bean.pojo.MarketRegionExample;
import com.cskaoyan.bean.vo.RegionCityListVO;
import com.cskaoyan.bean.vo.RegionListVO;
import com.cskaoyan.bean.vo.RegionProvinceListVO;
import com.cskaoyan.mapper.MarketRegionMapper;
import com.cskaoyan.service.RegionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 商场管理-行政区域
 * 创建日期: 2022/04/07 17:45
 *
 * @author HanWeiqi
 */
@Service
public class RegionServiceImpl implements RegionService {
    @Autowired
    MarketRegionMapper marketRegionMapper;


    @Override
    @Transactional
    public RegionListVO regionList() {
        MarketRegionExample province = new MarketRegionExample();

        MarketRegionExample.Criteria pCriteria = province.createCriteria();

        pCriteria.andPidEqualTo(0);

        List<MarketRegion> provinceRegion = marketRegionMapper.selectByExample(province);

        List<RegionProvinceListVO> provinces = new ArrayList<>();


        for (MarketRegion p : provinceRegion) {
            MarketRegionExample city = new MarketRegionExample();
            MarketRegionExample.Criteria cCriteria = city.createCriteria();

            // 根据省份id找城市
            cCriteria.andPidEqualTo(p.getId());
            List<MarketRegion> cityRegion = marketRegionMapper.selectByExample(city);
            List<RegionCityListVO> cities = new ArrayList<>();
            // 遍历城市列表，赋值给cityVO，然后添加到cities列表中
            for (MarketRegion c : cityRegion) {

                MarketRegionExample area = new MarketRegionExample();
                MarketRegionExample.Criteria aCriteria = area.createCriteria();

                // 根据城市id获取区
                aCriteria.andPidEqualTo(c.getId());
                List<MarketRegion> a = marketRegionMapper.selectByExample(area);

                cities.add(new RegionCityListVO(c.getId(),c.getName(),c.getType(),c.getCode(),a));


            }
            provinces.add(new RegionProvinceListVO(p.getId(),p.getName(),p.getType(),p.getCode(),cities));
        }

        PageInfo<RegionProvinceListVO> pageInfo = new PageInfo<>(provinces);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();


        return RegionListVO.data(total, pages, (int) total, pages,provinces);
    }
}
